import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from .models import ChatRoom, Message
from user.models import UserInfo

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = f'chat_{self.room_name}'

        # 加入房间组
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

        # 获取或创建房间
        room, created = ChatRoom.objects.get_or_create(name=self.room_name)

        # 加载历史消息
        messages = Message.objects.filter(room=room).order_by('timestamp')[:50]
        for message in messages:
            self.send(text_data=json.dumps({
                'message': message.content,
                'username': message.user.username,
                'user_id': message.user.id
            }))

    def disconnect(self, close_code):
        # 离开房间组
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        username = self.scope["user"].username if self.scope["user"].is_authenticated else '匿名用户'

        # 获取当前用户
        user = self.scope["user"]
        user_info = UserInfo.objects.get(username=user.username)

        # 获取或创建房间
        room, created = ChatRoom.objects.get_or_create(name=self.room_name)

        # 保存消息到数据库
        Message.objects.create(user=user_info, room=room, content=message)

        # 发送消息到房间组
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'username': username,
                'user_id': user_info.id
            }
        )

    def chat_message(self, event):
        message = event['message']
        username = event['username']
        user_id = event['user_id']

        # 发送消息到 WebSocket
        self.send(text_data=json.dumps({
            'message': message,
            'username': username,
            'user_id': user_id
        }))